<template>
  <div class='container'>
    <el-dialog :title="title" :visible="dialogFormVisible" width="400px" @close="closeDialog">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="学科名称" label-width="80px" prop="subjectName">
          <el-input v-model="form.subjectName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-switch
            style="display: block"
            v-model="form.isFrontDisplay"
            active-color="#13ce66"
            inactive-text="是否显示"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="addSubject">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects.js'
export default {
  name: 'subject',
  data () {
    const checkName = (rule, value, cb) => {
      if (this.form.id && value === this.form.subjectName) { cb() }
      this.tableData.forEach(item => {
        if (item.subjectName === value) {
          cb(new Error(`${value}学科已存在`))
        }
      })
      cb()
    }
    return {
      title: '',
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: ['blur', 'change'] },
          { validator: checkName, trigger: ['blur', 'change'] }
        ],
        isFrontDisplay: [
          { type: 'number', message: '请选择是否显示', tirgger: 'blur' }
        ]
      }
    }
  },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false
    },
    tableData: {
      type: Array,
      required: true
    },
    form: {
      type: Object,
      default: () => {
        return {
          subjectName: '',
          isFrontDisplay: true
        }
      }
    }
  },
  methods: {
    closeDialog () {
      this.$emit('update:dialogFormVisible', false)
      this.$refs.form.resetFields()
      this.$emit('update:form', {
        subjectName: '',
        isFrontDisplay: 1
      })
    },
    addSubject () {
      this.$refs.form.validate(async boo => {
        if (!boo) return this.$message.error('请按要求填写')
        if (this.title === '修改学科') {
          const res = await update(this.form)
          console.log(res)
          this.$message.success('修改成功')
        } else {
          const res = await add(this.form)
          console.log(res)
          this.$message.success('添加成功')
        }
        this.closeDialog()
        this.$emit('reload')
      })
    }
  }
}
</script>

<style scoped lang='scss'></style>
